/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Group;
import edu.cmu.fithub.db.bean.Posts;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.formbeans.LoginForm;
import edu.cmu.fithub.formbeans.RegisterForm;

public class DeleteGroupAction extends Action {

	private FormBeanFactory<LoginForm> formFactory = FormBeanFactory
			.getInstance(LoginForm.class);

	public DeleteGroupAction() {
	}

	public String getName() {
		return "deleteGroup.do";
	}

	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		User user = (User) request.getSession().getAttribute("user");
		String groupId = request.getParameter("groupId");
		Session dbSession = DBHelper.getSessionFactory().openSession();
		List<Group> groupList = dbSession.createCriteria(Group.class)
				.add(Restrictions.eq("adminId", user.getUserId()))
				.add(Restrictions.eq("groupId", Integer.parseInt(groupId)))
				.list();
		if (groupList.size() != 0) {
			// remove group and group members
			dbSession.beginTransaction();
			dbSession.delete(groupList.get(0));
			dbSession.getTransaction().commit();

			// remove all posts made in the group
			List<Posts> groupPostList = dbSession
					.createCriteria(Posts.class)
					.add(Restrictions.eq("groupId", groupList.get(0)
							.getGroupId())).list();
			for (Iterator iterator = groupPostList.iterator(); iterator
					.hasNext();) {
				Posts posts = (Posts) iterator.next();
				dbSession.beginTransaction();
				dbSession.delete(posts);
				dbSession.getTransaction().commit();
			}
		} else {
			errors.add("Either you are not allowed to delete this group or no such group exists!!!");
			return "error.jsp";
		}
		return "showGroups.do";
	}
}
